package com.heima.wemedia.service.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.message.NewsAutoScanConstants;
import com.heima.common.constants.message.NewsUpOrDownConstants;
import com.heima.common.constants.message.PublishArticleConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDTO;
import com.heima.model.wemedia.dtos.WmNewsDTO;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVO;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.el.ELClass;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

  @Value("${file.oss.web-site}")
  private String webSite;

  @Autowired
  private WmNewsMaterialMapper wmNewsMaterialMapper;

  @Autowired
  private WmMaterialMapper wmMaterialMapper;


    @Override
    public ResponseResult findList(WmNewsPageReqDTO dto) {
        //1.校验参数  分页  是否登录
        dto.checkParam();
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2.封装查询条件
        LambdaQueryWrapper<WmNews> queryWrapper = Wrappers.<WmNews>lambdaQuery();
        //2.1标题
        queryWrapper.like(StringUtils.isNotBlank(dto.getKeyword()),WmNews::getTitle,dto.getKeyword());
        //2.2频道
        queryWrapper.eq(dto.getChannelId()!=null,WmNews::getChannelId,dto.getChannelId());
        //2.3状态
        queryWrapper.eq(dto.getStatus()!=null,WmNews::getStatus,dto.getStatus());
        //2.4开始时间，结束时间
        queryWrapper.between(dto.getBeginPubDate()!=null&&dto.getEndPubDate()!=null,
                WmNews::getCreatedTime,
                dto.getBeginPubDate(),
                dto.getEndPubDate());
        //2.5登录用户id
        queryWrapper.eq(WmNews::getUserId,user.getId());
        //2.6设置创建时间降序
        queryWrapper.orderByDesc(WmNews::getCreatedTime);
        //3.封装分页条件
        Page<WmNews> pageReq = new Page<>(dto.getPage(), dto.getSize());
        //4.执行查询
        IPage<WmNews> pageResult = this.page(pageReq,queryWrapper);
        //5.返回结果
        PageResponseResult result = new PageResponseResult(dto.getPage(),dto.getSize(),
                            pageResult.getTotal(),pageResult.getRecords());
        // 设置图片前缀路径
        result.setHost(webSite);
        return result;
    }


    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult submitNews(WmNewsDTO dto) {
       //1.检查参数  封装WmNews对象
      WmNews wmNews = paresDtoToWmNews(dto);
      //2.保存或修改文章
        saveOrUpdateWmNews(wmNews);
        //3.保存  文章内容或封面和素材的关联关系
            //3.1 TODO:从文章内容中抽取所有的素材路径
       List<String> materialUrls = parseContentImages(wmNews.getContent());

            //3.2 TODO：保存文章内容引用素材的关联关系
        saveRelativeInfo(materialUrls,wmNews,WemediaConstants.WM_CONTENT_REFERENCE);
            //3.3 TODO：保存封面引用素材的关联关系
        saveRelativeInfoForCover(materialUrls,wmNews,dto);

        //4.TODO:发送MQ消息，触发异步的自动审核
        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE,wmNews.getId());
        log.info("成功发送文章自动审核消息  目的队列：{}  文章id：{} ",NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE,wmNews.getId());

        return ResponseResult.okResult();
    }





    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //1 参数检查
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2 执行查询
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3 返回结果
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }



    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult delNews(Integer id) {
        //1.检查参数
        if(id == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章Id不可缺少");
        }
        //2.获取数据
        WmNews wmNews = getById(id);
        if(wmNews == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.判断当前文章的状态  status==9  enable == 1
        if(wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())
                && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章已发布，不能删除");
        }
        //4.去除素材与文章的关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
        //5.删除文章
        removeById(wmNews.getId());
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult downOrUp(WmNewsDTO dto) {
        //1.检查参数
        if(dto == null || dto.getId() == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        Short enable = dto.getEnable();
        if(enable == null ||
                (!WemediaConstants.WM_NEWS_UP.equals(enable)&&!WemediaConstants.WM_NEWS_DOWN.equals(enable))){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"上下架状态错误");
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.判断文章是否发布
        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章不是发布状态，不能上下架");
        }
        //4.修改文章状态，同步到app端（后期做）TODO
        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId())
                .set(WmNews::getEnable,dto.getEnable()));

        if (WemediaConstants.WM_NEWS_DOWN.equals(enable)){
            //下架消息
            rabbitTemplate.convertAndSend(
                    NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                    NewsUpOrDownConstants.NEWS_DOWN_ROUTE_KEY,
                    wmNews.getArticleId()
            );
            log.info("成功发送文章  下架消息   文章id:{}",wmNews.getArticleId());
        }else {
            //上架消息
            rabbitTemplate.convertAndSend(
                    NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                    NewsUpOrDownConstants.NEWS_UP_ROUTE_KEY,
                    wmNews.getArticleId()
            );
            log.info("成功发送文章  上架消息   文章id:{}",wmNews.getArticleId());
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     *  保存文章封面和素材的关联关系
     * @param materialUrls
     * @param wmNews
     * @param dto
     */
    private void saveRelativeInfoForCover(List<String> materialUrls, WmNews wmNews, WmNewsDTO dto) {
        List<String> images = dto.getImages();
        //          判断前端传入type是否为-1
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            //           需要自动生成封面  规则
            int size = materialUrls.size();
            if (size==0) {
                //  内容中没有图片，则为无图
            wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }else if (size <= 2){
                //  内容图片的个数小于等于2  则为单图截图一张图
                images=materialUrls.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            }else {
                //   内容图片大于2，则为多图，截图三张图
                images=materialUrls.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            }
            if (!CollectionUtils.isEmpty(images)){
                wmNews.setImages(imagesToStr(images));
            }
            //修改文章
            this.updateById(wmNews);
        }
        if (!CollectionUtils.isEmpty(images)){
            images=images.stream().map(url -> url.replaceAll(webSite,"")).collect(Collectors.toList());
            //调用保存关联关系方法
            saveRelativeInfo(images,wmNews,WemediaConstants.WM_IMAGE_REFERENCE);
        }

    }


    /**
     *          保存素材和文章关联关系方法
     * @param materialUrls  素材的路径list
     * @param wmNews       文章
     * @param type          引用类型 0是代表内容引用  1是代表封面引用
     */
    private void saveRelativeInfo(List<String> materialUrls, WmNews wmNews, Short type) {
        //1.先根据素材路径集合  查询素材表  得到对应的id集合
//        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(
//                Wrappers.<WmMaterial>lambdaQuery()
//                        .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId())
//                        .in(WmMaterial::getUrl, materialUrls)
//                        //只返回id字段的值
//                        .select(WmMaterial::getId)
//        );
        List<Integer> ids = wmMaterialMapper.selectRelationsIds(materialUrls, WmThreadLocalUtils.getUser().getId());
        //2.判断id集合的数量  是否 等于 素材路径集合的数量， 不等于提示素材缺失
        if (ids.size() < materialUrls.size()){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"素材缺失");
        }
        //3. 批量的插入关联关系
//        for (WmMaterial wmMaterial : wmMaterials) {
//            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
//            wmNewsMaterial.setMaterialId(wmMaterial.getId());
//            wmNewsMaterial.setNewsId(wmNews.getId());
//            wmNewsMaterial.setType(type);
//            wmNewsMaterialMapper.insert(wmNewsMaterial);
//        }
        wmNewsMaterialMapper.saveRelations(ids,wmNews.getId(),type);
    }

    /**
     * 提取出内容中 锁涉及的素材路径
     * @param content
     * @return
     */
    private List<String> parseContentImages(String content) {
        List<Map> mapList = JSON.parseArray(content, Map.class);
      return  mapList.stream()   //创建流对象
        //集合中 找到所有type为image的map
                    .filter(x -> "image".equals(x.get("type")))
        //获取map的value字段值 得到路径
                    .map(x -> String.valueOf(x.get("value")))
        //替换掉路径的前缀
                    .map(url -> url.replaceAll(webSite,""))
        //去除重复的素材
                    .distinct()
        //将得到的素材返回路径集合
        .collect(Collectors.toList());
    }

    private void saveOrUpdateWmNews(WmNews wmNews) {
        //2.1WmNews信息补全（创建时间  上下架  发表用户id）
        wmNews.setCreatedTime(new Date());
            //文章状态 9
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP);
        //2.2判断id是否为空，为空保存wmNews
        if (wmNews.getId()==null){
             // 为空保存
            this.save(wmNews);
        }else {
            //2.3如果不为空  修改wmNews 修改前要先将 文章和素材 的关联关系删除
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            this.updateById(wmNews);
        }
        //2.3如果不为空  修改WmNews 修改前要先将  文章和素材的关联关系删除

    }

    private WmNews paresDtoToWmNews(WmNewsDTO dto) {
        //1.1检查内容  标题 是否登录
        if (StringUtils.isBlank(dto.getTitle()) || StringUtils.isBlank(dto.getContent())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章的标题和内容不能为空");
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"请先登录");
        }
        //1.2dto拷贝属性WmNews
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);
        //1.3type：如果type为-1 暂时将WmNews中的type设置为null
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())){
            wmNews.setType(null);
        }
        //1.4dto中的images是list  wmNews的images是字符串
        if (!CollectionUtils.isEmpty(dto.getImages())){
            wmNews.setImages(imagesToStr(dto.getImages()));
        }
        //1.5补全id
        wmNews.setUserId(user.getId());
        return wmNews;
    }

    /**
     * 将字符串集合转为字符串用逗号拼接
     * @param images
     * @return
     */
    private String imagesToStr(List<String> images) {
        return images.stream()  //创建流对象
                // 替换路径中的访问前缀
                .map(url -> url.replaceAll(webSite,""))
                // 将字符串  使用逗号拼接
                .collect(Collectors.joining(","));
    }



    @Autowired
    WmNewsMapper wmNewsMapper;
    /**
     * 查询文章列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(NewsAuthDTO dto) {
        //1.检查参数
        dto.checkParam();
        //记录当前页
        int currentPage = dto.getPage();
        //设置起始页
        dto.setPage((dto.getPage()-1)*dto.getSize());

        if(StringUtils.isNotBlank(dto.getTitle())){
            //  concat(%,?,%)
            dto.setTitle("%"+dto.getTitle()+"%");
        }

        //2.分页查询
        List<WmNewsVO> wmNewsVoList = wmNewsMapper.findListAndPage(dto);
        //统计多少条数据
        long count = wmNewsMapper.findListCount(dto);

        //3.结果返回
        ResponseResult result = new PageResponseResult(currentPage, dto.getSize(), count, wmNewsVoList);
        result.setHost(webSite);
        return result;
    }


    @Autowired
    WmUserMapper wmUserMapper;

    /**
     * 查询文章详情
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        //1参数检查
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章信息
        WmNews wmNews = getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.查询作者
        WmUser wmUser = null;
        if(wmNews.getUserId() != null){
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }

        //4.封装vo信息返回
        WmNewsVO wmNewsVo = new WmNewsVO();
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        if(wmUser != null){
            wmNewsVo.setAuthorName(wmUser.getName());
        }
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(webSite);
        return responseResult;
    }




    /**
     * 自媒体文章人工审核
     * @param status 2  审核失败  4 审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDTO dto) {
        //1.参数检查
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 检查文章状态 不能为9  已发布
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章已发布");
        }
        //3.修改文章状态
        wmNews.setStatus(status);
        if(StringUtils.isNotBlank(dto.getMsg())){
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);

        // TODO 通知定时发布文章
        if (WemediaConstants.WM_NEWS_AUTH_PASS.equals(status)){
            //1. 获取发布时间
            long publishTime = wmNews.getPublishTime().getTime();
            //2. 获取当前时间
            long nowTime = System.currentTimeMillis();
            //3.距离发布时间=发布时间-当前时间
            long remainTime = publishTime - nowTime;
            //4.发送消息，并设置消息头 x-delay ：距离发布时间
            rabbitTemplate.convertAndSend(
                    PublishArticleConstants.DELAY_DIRECT_EXCHANGE,
                    PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY,
                    wmNews.getId(),
                    new MessagePostProcessor() {
                        /**
                         *      消息后置处理器  用于改变消息属性
                         * @param message
                         * @return
                         * @throws AmqpException
                         */
                        @Override
                        public Message postProcessMessage(Message message) throws AmqpException {
                            message.getMessageProperties()
                                    .setHeader("x-delay",remainTime<=0?0:remainTime);  //如果这个时间小于等于零就取零 相反就取这个时间
                            return message;
                        }
                    }
            );
            log.info("成功发送文章代发布消息，  文章id：{}   延时时间：{} ",wmNews.getId(),remainTime);

        }


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
